/*
 * @Author: 姚潘涛
 * @Date: 2024-04-08 20:36:40
 * @LastEditors: 姚潘涛
 * @LastEditTime: 2024-05-29 15:03:30
 * @FilePath:
 * /xict_ws/src/xcmg-intelligent-cockpit-three/src/xict_ui/src/xict_ui_core/vehiclemanage.cpp
 * @Description:
 *
 * Copyright (c) 2024 by pandaman, All Rights Reserved.
 */
#include "xict_ui_core/vehiclemanage.h"
#include "xict_ui_common/utils/config.h"
#include <QDebug>
#include <QProcess>
#include <QTextCodec>

namespace xict_ui_core {
    VehicleManage* VehicleManage::getInstance() {
        static VehicleManage _instance;
        return &_instance;
    }

    VehicleManage::VehicleManage(QObject* parent) : QThread(parent) { }

    void VehicleManage::init(QString json_path) {
        if (json_path.isEmpty())
            json_path = "../../assets/vehicle.json";
        xict_ui_common::Config::GetInstance().GetYamlArray(json_path,
                                                           vehicleArray);
        setrun_flag(true);
    }
    void VehicleManage::run() {
        while (run_flag()) {
            if (connect_flag()) {
                QString ping_time =
                    net_tool_.getPingTime(current_vehicle_host());
                emit signalVehiclePingTime(ping_time);
            } else {
                for (QJsonArray::Iterator it = vehicleArray.begin();
                     it != vehicleArray.end(); it++) {
                    QJsonObject obj = it[0].toObject();
                    if (net_tool_.checkPing(
                            obj["host"]
                                .toString())) {   // 查看是否能ping通（阻塞）
                        obj.insert("state", "在线");
                    } else {
                        obj.insert("state", "离线");
                    }
                    it[0] = obj;
                }
                QJsonDocument doc;
                doc.setArray(vehicleArray);
                QString json_str = QString::fromUtf8(
                    doc.toJson(QJsonDocument::Compact).constData());
                // qDebug() << json_str;
                emit signalVehiclesInfo(json_str);
            }
            sleep(1);
        }
    }

}   // namespace xict_ui_core
